package net.pingfang.devicelock;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import lombok.extern.slf4j.Slf4j;
import net.pingfang.devicelock.util.DeviceDecodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
@Slf4j
@Service
public class NettyClientService {
    private Bootstrap bootstrap;
    private Channel channel;

    private final ThreadPoolTaskExecutor taskExecutor;

    public NettyClientService(@Qualifier("bootstrap")Bootstrap bootstrap,
                              @Qualifier("tcpTaskExecutor")ThreadPoolTaskExecutor taskExecutor){
        this.bootstrap = bootstrap;
        this.taskExecutor = taskExecutor;
    }

    private final ThreadLocal<SimpleDateFormat> threadLocalSdf =
            ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMddHHmmss"));

    @PostConstruct
    public void connect() throws InterruptedException {
        ChannelFuture future = bootstrap.connect().sync();
        this.channel = future.channel();
//        log.info("Netty client connected to {}:{}",
//                bootstrap.config().remoteAddress());
    }

    public void sendBytes(String LockName,String passWord) {
        taskExecutor.execute(()->{
            if (channel != null && channel.isActive()) {
                String formattedTime = threadLocalSdf.get().format(new Date());
                Message<byte[]> msg = MessageBuilder.withPayload(
                        DeviceDecodeUtil.LockCmd(LockName,passWord,formattedTime)).build();
                channel.writeAndFlush(Unpooled.copiedBuffer(msg.getPayload()));
            }
        });

    }



    @PreDestroy
    public void shutdown() {
        if (channel != null) {
            channel.close().syncUninterruptibly();
        }
    }
}
